package com.linwen.excise.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName TreeUtil
 * @Description TODO
 * @Author zero
 * @DATE 2024/4/28 3:37 AM
 * @Version 1.0
 */
public class TreeUtil {

    public static TreeNode buildTree(int[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        Queue<TreeNode> rootQueue = new LinkedList<>();
        TreeNode root = new TreeNode(arr[0]);
        int index = 1;
        rootQueue.add(root);
        while (!rootQueue.isEmpty()) {
            TreeNode rootNode = rootQueue.poll();
            if (rootNode != null) {
                if (index < arr.length) {
                    int i = arr[index++];
                    if(i==0){
                        rootNode.left = null;
                    }else{
                        TreeNode leftNode = new TreeNode(i);
                        rootNode.left = leftNode;
                        rootQueue.add(leftNode);
                    }
                }
                if (index < arr.length) {
                    int i = arr[index++];
                    if(i==0){
                        rootNode.right = null;
                    }else {
                        TreeNode rightNode = new TreeNode(i);
                        rootNode.right = rightNode;
                        rootQueue.add(rightNode);
                    }
                }
            } else {
                index = index + 2;
            }
        }
        return root;
    }
}
